import axios from 'axios'
import { message } from 'ant-design-vue'

const http = axios.create()

http.interceptors.request.use((config) => {
  const rootStr: string = localStorage.getItem('persist:root') || ''
  if (!rootStr) {
    return config
  }
  const rootInfo: { common_data: string } = JSON.parse(rootStr)
  const { common_data } = rootInfo
  if (!common_data) {
    return config
  }
  const userInfo: { token: string } = JSON.parse(common_data)
  const { token } = userInfo
  if (token) {
    config.headers['x-token'] = token
  }
  return config
}, error => {
  return Promise.reject(error)
})

http.interceptors.response.use((response) => {
  const { data } = response
  if (data.code !== 200) {
    message.error('请求错误')
  }
  return response
}, error => {
  return Promise.reject(error)
})

export default http